package com.frejoys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.frejoys.common.dto.admin.AdminVerifyDto;
import com.frejoys.common.dto.admin.AdminVerifyListDto;
import com.frejoys.common.dto.admin.SubmitVerifyDto;
import com.frejoys.common.dto.app.StoreEnterUpdateStatusDto;
import com.frejoys.common.dto.common.PageDto;
import com.frejoys.common.enums.EAdminVerifyStatus;
import com.frejoys.common.enums.EAdminVerifyType;
import com.frejoys.common.enums.EFileSize;
import com.frejoys.common.enums.EShelves;
import com.frejoys.common.enums.EStatus;
import com.frejoys.common.enums.EStoreActivityType;
import com.frejoys.common.enums.EStoreUserRole;
import com.frejoys.common.enums.EUserRole;
import com.frejoys.common.enums.EVerifyResultType;
import com.frejoys.common.enums.EVerifyStatus;
import com.frejoys.common.error.HttpStatus;
import com.frejoys.common.exception.GeneralException;
import com.frejoys.common.util.AppConfigUtil;
import com.frejoys.common.util.CommonUtil;
import com.frejoys.common.util.TimeUtil;
import com.frejoys.common.vo.admin.AdminVerifyActivityListVo;
import com.frejoys.common.vo.admin.AdminVerifyGoodsListVo;
import com.frejoys.common.vo.admin.AdminVerifyListVo;
import com.frejoys.common.vo.admin.AdminVerifyStoreEnterListVo;
import com.frejoys.common.vo.admin.AdminVerifyStoreListVo;
import com.frejoys.common.vo.app.VerifyActivityListVo;
import com.frejoys.common.vo.app.VerifyGoodsListVo;
import com.frejoys.common.vo.app.VerifyListVo;
import com.frejoys.common.vo.app.VerifyStoreListVo;
import com.frejoys.dao.entity.AdminVerify;
import com.frejoys.dao.entity.AgentStore;
import com.frejoys.dao.entity.Goods;
import com.frejoys.dao.entity.Store;
import com.frejoys.dao.entity.StoreActivity;
import com.frejoys.dao.entity.StoreEnter;
import com.frejoys.dao.entity.StoreUser;
import com.frejoys.dao.entity.User;
import com.frejoys.dao.mapper.AdminVerifyMapper;
import com.frejoys.dao.mapper.AgentStoreMapper;
import com.frejoys.dao.mapper.GoodsMapper;
import com.frejoys.dao.mapper.StoreActivityMapper;
import com.frejoys.dao.mapper.StoreEnterMapper;
import com.frejoys.dao.mapper.StoreMapper;
import com.frejoys.dao.mapper.StoreUserMapper;
import com.frejoys.dao.mapper.UserMapper;
import com.frejoys.service.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@RequiredArgsConstructor
public class AdminVerifyServiceImpl extends ServiceImpl<AdminVerifyMapper, AdminVerify> implements AdminVerifyService {


    private final StoreService storeService;

    private final StoreMapper storeMapper;

    private final CategoryService categoryService;

    private final ReasonService reasonService;

    private final GoodsMapper goodsMapper;

    private final StoreActivityMapper storeActivityMapper;

    private final UserMapper userMapper;

    private final UserService userService;

    private final StoreEnterMapper storeEnterMapper;

    private final AgentStoreMapper agentStoreMapper;

    private final AreaService areaService;

    private final ActivityService activityService;

    private final StoreUserMapper storeUserMapper;

    private final AuthRuleService authRuleService;

    @Override
    public Page<AdminVerify> getListByType(AdminVerifyListDto dto) {
        Page<AdminVerify> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<AdminVerify> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(dto.getType() != null, AdminVerify::getType, dto.getType());
        lambdaQueryWrapper.in(!CollectionUtils.isEmpty(dto.getIds()), AdminVerify::getId, dto.getIds())
                .last("ORDER BY FIELD(status, " + EAdminVerifyStatus.agentPass.getValue()+ " )DESC,FIELD(status,  " + EAdminVerifyStatus.initial.getValue()+")DESC ,update_time desc");
        return baseMapper.selectPage(page, lambdaQueryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean submitVerify(SubmitVerifyDto dto) {
        // 查询该审核是否存在
        LambdaQueryWrapper<AdminVerify> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AdminVerify::getType, dto.getType());
        lambdaQueryWrapper.eq(AdminVerify::getCommonId, dto.getCommonId());
        lambdaQueryWrapper.and(qw -> {
            qw.eq(AdminVerify::getStatus, EVerifyStatus.pending.getValue());
            qw.or();
            qw.eq(AdminVerify::getStatus, EVerifyStatus.agentPass.getValue());
        });
        // 存在待审核时,不允许再次提交
        if (baseMapper.exists(lambdaQueryWrapper)) {
            throw new GeneralException(HttpStatus.verifyPendingError);
        }
        // 提交店铺审核时,必须存在有效商品及活动才允许上架店铺
//        if (EAdminVerifyType.store.getValue().equals(dto.getType())) {
//            LambdaQueryWrapper<Goods> goodsQw = new LambdaQueryWrapper<>();
//            goodsQw.eq(Goods::getStoreId,dto.getCommonId());
//            goodsQw.eq(Goods::getStatus,EStatus.on.getValue());
//            goodsQw.eq(Goods::getShelves,EShelves.onSale.getValue());
//            if (!goodsMapper.exists(goodsQw)) {
//                throw new GeneralException(HttpStatus.invalidGoodsError);
//
//            }
//            LambdaQueryWrapper<StoreActivity> activityQw = new LambdaQueryWrapper<>();
//            activityQw.eq(StoreActivity::getStoreId,dto.getCommonId());
//            activityQw.eq(StoreActivity::getStatus,EStatus.on.getValue());
//            activityQw.eq(StoreActivity::getShelves,EShelves.onSale.getValue());
//            int unixTime = TimeUtil.unixTime();
//            activityQw.lt(StoreActivity::getStartTime,unixTime);
//            activityQw.gt(StoreActivity::getEndTime,unixTime);
//            if (!storeActivityMapper.exists(activityQw)) {
//                throw new GeneralException(HttpStatus.invalidActivityError);
//            }
//
//        }

        // 修改为上架申请中
        if (dto.getType().equals(EAdminVerifyType.store.getValue())) {
            LambdaQueryWrapper<Store> qw = new LambdaQueryWrapper<>();
            qw.eq(Store::getId, dto.getCommonId());
            qw.eq(Store::getShelves, EShelves.onSale.getValue());
            if (storeMapper.exists(qw)) {
                throw new GeneralException(HttpStatus.alreadyOnSaleError);
            }

            LambdaUpdateWrapper<Store> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(Store::getShelves, EShelves.applyfor.getValue());
            updateWrapper.eq(Store::getId, dto.getCommonId());
            if (storeMapper.update(updateWrapper) < 1) {
                throw new GeneralException(HttpStatus.storeNotFound);
            }
        } else if (dto.getType().equals(EAdminVerifyType.goods.getValue())) {

            LambdaQueryWrapper<Goods> qw = new LambdaQueryWrapper<>();
            qw.eq(Goods::getId, dto.getCommonId());
            qw.eq(Goods::getShelves, EShelves.onSale.getValue());
            if (goodsMapper.exists(qw)) {
                throw new GeneralException(HttpStatus.alreadyOnSaleError);
            }

            Goods goods = goodsMapper.selectOne(Wrappers.<Goods>lambdaQuery().select(Goods::getStoreId)
                    .eq(Goods::getId, dto.getCommonId()).last(" limit 1"));

            Store store = storeMapper.selectOne(Wrappers.<Store>lambdaQuery().select(Store::getId, Store::getStatus, Store::getShelves)
                    .eq(Store::getId, goods.getStoreId()).last(" limit 1"));

            if (ObjectUtil.isEmpty(store)) {
                throw new GeneralException(HttpStatus.storeNotFound);
            }

            if (store.getStatus() < EStatus.on.getValue()) {
                throw new GeneralException(HttpStatus.storeStatusIsFail);
            }
//
//            if (store.getShelves() < EShelves.onSale.getValue()) {
//                throw new GeneralException(HttpStatus.storeIsNotOnSaleGoodsOnFail);
//            }

            LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(Goods::getShelves, EShelves.applyfor.getValue());
            updateWrapper.eq(Goods::getId, dto.getCommonId());
            if (goodsMapper.update(updateWrapper) < 1) {
                throw new GeneralException(HttpStatus.goodsNotFound);
            }
        } else if (dto.getType().equals(EAdminVerifyType.activity.getValue())) {

            LambdaQueryWrapper<StoreActivity> qw = new LambdaQueryWrapper<>();
            qw.eq(StoreActivity::getId, dto.getCommonId());
            qw.eq(StoreActivity::getShelves, EShelves.onSale.getValue());
            if (storeActivityMapper.exists(qw)) {
                throw new GeneralException(HttpStatus.alreadyOnSaleError);
            }

            StoreActivity storeActivity = storeActivityMapper.selectOne(Wrappers.<StoreActivity>lambdaQuery().select(StoreActivity::getStoreId, StoreActivity::getStartTime,
                            StoreActivity::getEndTime)
                    .eq(StoreActivity::getId, dto.getCommonId()).last(" limit 1"));

            Store store = storeMapper.selectOne(Wrappers.<Store>lambdaQuery().select(Store::getId, Store::getStatus, Store::getShelves)
                    .eq(Store::getId, storeActivity.getStoreId()).last(" limit 1"));

            //同一时刻只能上架一个活动
            Integer num = storeActivityMapper.getStoreActivity(storeActivity.getStoreId(), storeActivity.getStartTime(), storeActivity.getEndTime());
            if(num > 0){
                throw new GeneralException(HttpStatus.storeActivityHasExit);
            }

            if (ObjectUtil.isEmpty(store)) {
                throw new GeneralException(HttpStatus.storeNotFound);
            }

            if (store.getStatus() < EStatus.on.getValue()) {
                throw new GeneralException(HttpStatus.storeStatusIsFail);
            }
//
//            if (store.getShelves() < EShelves.onSale.getValue()) {
//                throw new GeneralException(HttpStatus.storeIsNotOnSaleGoodsOnFail);
//            }
            LambdaUpdateWrapper<StoreActivity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(StoreActivity::getShelves, EShelves.applyfor.getValue());
            updateWrapper.eq(StoreActivity::getId, dto.getCommonId());
            if (storeActivityMapper.update(updateWrapper) < 1) {
                throw new GeneralException(HttpStatus.activityNotFound);
            }
        }

        // 插入审核记录
        AdminVerify adminVerify = new AdminVerify();
        adminVerify.setType(dto.getType());
        adminVerify.setCommonId(dto.getCommonId());
        adminVerify.setStatus(EVerifyStatus.pending.getValue());
        adminVerify.setCreateTime(TimeUtil.unixTime());
        adminVerify.setUpdateTime(TimeUtil.unixTime());
        return save(adminVerify);
    }

    @Override
    public IPage<AdminVerifyStoreEnterListVo> listStoreEnterInfo(AdminVerifyListDto dto) {
        // 分页查询审核信息
        Page<AdminVerify> verifyPage = getListByType(dto);
        IPage<AdminVerifyStoreEnterListVo> voPage = verifyPage.convert(adminVerify -> BeanUtil.copyProperties(adminVerify, AdminVerifyStoreEnterListVo.class));
        List<AdminVerifyStoreEnterListVo> voList = voPage.getRecords();
        if (CollectionUtils.isEmpty(voList)) {
            return voPage;
        }

        // 查询驳回原因
        List<Integer> reasonId = voList.stream().map(AdminVerifyStoreEnterListVo::getReasonId).toList();
        Map<Integer, String> reasonIdNameMap = reasonService.getIdNameMap(reasonId);


        // 查询商家入驻申请信息
        List<Integer> storeEnterIdList = voList.stream().map(AdminVerifyStoreEnterListVo::getCommonId).collect(Collectors.toList());
        LambdaQueryWrapper<StoreEnter> storeEnterQw = new LambdaQueryWrapper<>();
        storeEnterQw.in(StoreEnter::getId, storeEnterIdList);
        List<StoreEnter> storeEnters = storeEnterMapper.selectList(storeEnterQw);
        Map<Integer, StoreEnter> storeEnterMap = storeEnters.stream().collect(Collectors.toMap(StoreEnter::getId, Function.identity()));

        //查询代理人
        List<Long> agentUserIdList = storeEnters.stream().map(StoreEnter::getAgentUserId).collect(Collectors.toList());
        LambdaQueryWrapper<User> userQw = new LambdaQueryWrapper<>();
        userQw.in(User::getId, agentUserIdList);
        List<User> users = userMapper.selectList(userQw);
        Map<Long, User> userMap = users.stream().collect(Collectors.toMap(User::getId, Function.identity()));

        //查询用户信息
        List<Long> userIds = storeEnters.stream().map(StoreEnter::getUserId).toList();
        List<User> userList = userMapper.getUserByIds(userIds);
        Map<Long, User> userMaps = userList.stream().collect(Collectors.toMap(User::getId, user -> user));

        for (AdminVerifyStoreEnterListVo vo : voList) {
            if (storeEnterMap.containsKey(vo.getCommonId())) {
                StoreEnter storeEnter = storeEnterMap.get(vo.getCommonId());
                vo.setUserId(storeEnter.getUserId());
                vo.setAgentUserId(storeEnter.getAgentUserId());
                if (storeEnter.getAgentUserId() != null && userMap.containsKey(storeEnter.getAgentUserId())) {
                    User agentUser = userMap.get(storeEnter.getAgentUserId());
                    vo.setAgentUserNickName(agentUser.getNickname());
                    vo.setAgentUserPhone(agentUser.getPhone());
                }
                if (userMaps.containsKey(vo.getUserId())){
                    vo.setNickname(userMaps.get(vo.getUserId()).getNickname());
                    vo.setPhone(userMaps.get(vo.getUserId()).getPhone());
                }
                vo.setName(storeEnter.getName());
                vo.setTel(storeEnter.getTel());
                vo.setBusinessLicenseUrl(AppConfigUtil.getUrlPrefix(storeEnter.getBusinessLicense()));
                vo.setIdCardImageUrl(AppConfigUtil.getUrlPrefix(storeEnter.getIdCardImage()));

                vo.setReason(reasonIdNameMap.get(vo.getReasonId()));
            }
        }

        return voPage;
    }

    @Override
    public IPage<AdminVerifyStoreListVo> listStoreInfo(AdminVerifyListDto dto) {

        // 分页查询审核信息
        Page<AdminVerify> verifyPage = getListByType(dto);
        IPage<AdminVerifyStoreListVo> voPage = verifyPage.convert(adminVerify -> BeanUtil.copyProperties(adminVerify, AdminVerifyStoreListVo.class));
        List<AdminVerifyStoreListVo> voList = voPage.getRecords();
        if (CollectionUtils.isEmpty(voList)) {
            return voPage;
        }

        // 查询店铺信息
        List<Integer> storeIdList = voList.stream().map(AdminVerifyStoreListVo::getCommonId).collect(Collectors.toList());
        LambdaQueryWrapper<Store> storeEnterQw = new LambdaQueryWrapper<>();
        storeEnterQw.in(Store::getId, storeIdList);
        List<Store> stores = storeMapper.selectList(storeEnterQw);
        Map<Integer, Store> storeMap = stores.stream().collect(Collectors.toMap(Store::getId, Function.identity()));
        // 查询品类信息
        List<Integer> categoryIdList = stores.stream().map(Store::getCategoryId).toList();
        Map<Integer, String> categoryIdNameMap = categoryService.getIdNameMap(categoryIdList);

        // 查询驳回原因
        List<Integer> reasonId = voList.stream().map(AdminVerifyStoreListVo::getReasonId).toList();
        Map<Integer, String> reasonIdNameMap = reasonService.getIdNameMap(reasonId);

        //查询申请人信息
        Map<Integer, User> map = getUserMessage(storeIdList);

        // 查询店铺待审商品
//        LambdaQueryWrapper<Goods> goodsQw = new LambdaQueryWrapper<>();
//        goodsQw.select(Goods::getId);
//        goodsQw.eq(Goods::getStatus,EShelves.applyfor.getValue());
//        goodsQw.in(Goods::getStoreId,storeMap.keySet());
//        List<Goods> goods = goodsMapper.selectList(goodsQw);

//        // 查询商品审核表id   storeid,goodsVerifyId
//        List<Integer> goodsId = goods.stream().map(Goods::getId).collect(Collectors.toList());
//        LambdaQueryWrapper<AdminVerify> adminVerifyQw = new LambdaQueryWrapper<>();
//        adminVerifyQw.eq(AdminVerify::getType,EAdminVerifyType.goods.getValue());
//        adminVerifyQw.in(AdminVerify::getCommonId,goodsId);
//        adminVerifyMapper.selectList(adminVerifyQw);

        Map<String, String> areaMap = areaService.getNameMap();

        // 补充店铺信息
        for (AdminVerifyStoreListVo adminVerifyStoreListVo : voList) {
            if (storeMap.containsKey(adminVerifyStoreListVo.getCommonId())) {
                Store store = storeMap.get(adminVerifyStoreListVo.getCommonId());
                BeanUtil.copyProperties(store, adminVerifyStoreListVo, "id","status","createTime","updateTime");
                adminVerifyStoreListVo.setCoverUrl(AppConfigUtil.getUrlPrefix(store.getCover()));
                adminVerifyStoreListVo.setCoverShowUrl(AppConfigUtil.getUrlPrefix(store.getCoverShow()));
                adminVerifyStoreListVo.setLogoUrl(AppConfigUtil.getUrlPrefix(store.getLogo(), EFileSize.logo.getValue()));
                adminVerifyStoreListVo.setCategoryName(categoryIdNameMap.get(adminVerifyStoreListVo.getCategoryId()));
                adminVerifyStoreListVo.setReason(reasonIdNameMap.get(adminVerifyStoreListVo.getReasonId()));
                adminVerifyStoreListVo.setProvinceName(areaMap.get(store.getProvince()));
                adminVerifyStoreListVo.setCityName(areaMap.get(store.getCity()));
                adminVerifyStoreListVo.setDistrictName(areaMap.get(store.getDistrict()));

            }
            User user = map.get(adminVerifyStoreListVo.getCommonId());
            if (user != null){
                adminVerifyStoreListVo.setNickname(user.getNickname());
                adminVerifyStoreListVo.setPhone(user.getPhone());
            }
        }
        return voPage;
    }

    @Override
    public IPage<AdminVerifyGoodsListVo> listGoodsInfo(AdminVerifyListDto dto) {

        // 分页查询审核信息
        Page<AdminVerify> verifyPage = getListByType(dto);
        IPage<AdminVerifyGoodsListVo> voPage = verifyPage.convert(adminVerify -> BeanUtil.copyProperties(adminVerify, AdminVerifyGoodsListVo.class));
        List<AdminVerifyGoodsListVo> voList = voPage.getRecords();
        if (CollectionUtils.isEmpty(voList)) {
            return voPage;
        }

        // 查询商品信息
        List<Integer> goodsIdList = voList.stream().map(AdminVerifyGoodsListVo::getCommonId).distinct().collect(Collectors.toList());
        LambdaQueryWrapper<Goods> storeEnterQw = new LambdaQueryWrapper<>();
        storeEnterQw.in(Goods::getId, goodsIdList);
        List<Goods> goods = goodsMapper.selectList(storeEnterQw);
        Map<Integer, Goods> goodsMap = goods.stream().collect(Collectors.toMap(Goods::getId, Function.identity()));

        // 查询驳回原因
        List<Integer> reasonId = voList.stream().map(AdminVerifyGoodsListVo::getReasonId).toList();
        Map<Integer, String> reasonIdNameMap = reasonService.getIdNameMap(reasonId);

        // 查询品类名称
        List<Integer> categoryIdList = goods.stream().map(Goods::getCategoryId).toList();
        Map<Integer, String> categoryIdNameMap = categoryService.getIdNameMap(categoryIdList);

        // 查询店铺名称
        List<Integer> storeIdList = goods.stream().map(Goods::getStoreId).toList();
        Map<Integer, String> storeIdNameMap = storeService.getIdNameMap(storeIdList);

        //查询申请人信息
        Map<Integer, User> map = getUserMessage(storeIdList);

        // 补充商品信息
        for (AdminVerifyGoodsListVo goodsVo : voList) {
            if (goodsMap.containsKey(goodsVo.getCommonId())) {
                Goods store = goodsMap.get(goodsVo.getCommonId());
                BeanUtil.copyProperties(store, goodsVo, "id","status");
                goodsVo.setCategoryName(categoryIdNameMap.get(goodsVo.getCategoryId()));
                goodsVo.setReason(reasonIdNameMap.get(goodsVo.getReasonId()));
                goodsVo.setStoreName(storeIdNameMap.get(goodsVo.getStoreId()));
                goodsVo.setCoverUrl(AppConfigUtil.getUrlPrefix(store.getCover()));
            }
            User user = map.get(goodsVo.getCommonId());
            if (user != null){
                goodsVo.setNickname(user.getNickname());
                goodsVo.setPhone(user.getPhone());
            }
        }
        return voPage;
    }

    @Override
    public IPage<AdminVerifyActivityListVo> listActivityInfo(AdminVerifyListDto dto) {
        // 分页查询审核信息
        Page<AdminVerify> verifyPage = getListByType(dto);
        IPage<AdminVerifyActivityListVo> voPage = verifyPage.convert(adminVerify -> BeanUtil.copyProperties(adminVerify, AdminVerifyActivityListVo.class));
        List<AdminVerifyActivityListVo> voList = voPage.getRecords();
        if (CollectionUtils.isEmpty(voList)) {
            return voPage;
        }

        // 查询活动信息
        List<Integer> activityIdList = voList.stream().map(AdminVerifyActivityListVo::getCommonId).collect(Collectors.toList());
        LambdaQueryWrapper<StoreActivity> storeEnterQw = new LambdaQueryWrapper<>();
        storeEnterQw.in(StoreActivity::getId, activityIdList);
        List<StoreActivity> activityList = storeActivityMapper.selectList(storeEnterQw);
        Map<Integer, StoreActivity> activityMap = activityList.stream().collect(Collectors.toMap(StoreActivity::getId, Function.identity()));
        List<Integer> storeIdList = activityList.stream().map(StoreActivity::getStoreId).toList();
        // 查询店铺名称
        Map<Integer, String> storeIdNameMap = storeService.getIdNameMap(storeIdList);

        //查询申请人信息
        Map<Integer, User> map = getUserMessage(storeIdList);

        Map<Integer, String> typeNameMap = activityService.getTypeNameMap();

        // 查询驳回原因
        List<Integer> reasonId = voList.stream().map(AdminVerifyActivityListVo::getReasonId).toList();
        Map<Integer, String> reasonIdNameMap = reasonService.getIdNameMap(reasonId);
        for (AdminVerifyActivityListVo vo : voList) {
            if (activityMap.containsKey(vo.getCommonId())) {
                StoreActivity activity = activityMap.get(vo.getCommonId());
                BeanUtil.copyProperties(activity, vo, "id","status");
                vo.setActivityType(activity.getType());
                vo.setStoreName(storeIdNameMap.get(vo.getStoreId()));
                vo.setActivityName(typeNameMap.get(vo.getActivityType()));
                vo.setReason(reasonIdNameMap.get(vo.getReasonId()));
            }
            User user = map.get(vo.getStoreId());
            if (user != null){
                vo.setNickname(user.getNickname());
                vo.setPhone(user.getPhone());
            }
        }
        return voPage;
    }


    @Override
    public List<VerifyStoreListVo> verifyStoreList(Long userId, PageDto dto) {
        Page page = new Page<>(dto.getPage(), dto.getSize());
        page.setSearchCount(false);

        List<VerifyStoreListVo> list = new ArrayList<>();

        LambdaQueryWrapper<AgentStore> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(AgentStore::getStoreId)
                .eq(AgentStore::getAgentUserId, userId);
        List<AgentStore> agentStores = agentStoreMapper.selectList(wrapper);

        if (!agentStores.isEmpty()) {
            List<Integer> agentStoreIds = agentStores.stream().map(AgentStore::getStoreId).toList();

            list = baseMapper.storeList(page, agentStoreIds, EAdminVerifyType.store.getValue());

            if (!list.isEmpty()) {

                //用户信息
                List<Long> userIds = list.stream().map(VerifyStoreListVo::getUserId).toList();
                List<User> userList = userMapper.getUserList(userIds, EStatus.on.getValue());
                Map<Long, String> userMap = userList.stream().collect(Collectors.toMap(User::getId, User::getNickname));

                //店铺信息
                List<Integer> storeIds = list.stream().map(VerifyStoreListVo::getStoreId).toList();
                List<Store> storeList = storeMapper.getStoreList(storeIds);
                Map<Integer, Store> storeMap = storeList.stream().collect(Collectors.toMap(Store::getId, store -> store));

                Map<String, String> areaMap = areaService.getNameMap();

                for (VerifyStoreListVo vo : list) {

                    if (userMap.containsKey(vo.getUserId())) {
                        vo.setNickname(userMap.get(vo.getUserId()));
                    }
                    if (storeMap.containsKey(vo.getStoreId())) {
                        Store store = storeMap.get(vo.getStoreId());
                        vo.setName(store.getName());
                        vo.setProvinceName(areaMap.get(store.getProvince()));
                        vo.setCityName(areaMap.get(store.getCity()));
                        vo.setDistrictName(areaMap.get(store.getDistrict()));
                        vo.setStreet(store.getStreet());
                        vo.setAddress(store.getAddress());
                        vo.setTel(store.getTel());
                        vo.setLogo(AppConfigUtil.getUrlPrefix(store.getLogo(),EFileSize.logo.getValue()));
                        vo.setCover(AppConfigUtil.getUrlPrefix(store.getCover()));
                        vo.setCoverShow(AppConfigUtil.getUrlPrefix(store.getCoverShow()));
                        vo.setStartTime(store.getStartTime());
                        vo.setEndTime(store.getEndTime());
                    }
                }
            }
        }

        return list;
    }


    @Override
    public List<VerifyGoodsListVo> verifyGoodsList(Long userId, PageDto dto) {
        Page page = new Page<>(dto.getPage(), dto.getSize());
        page.setSearchCount(false);

        List<VerifyGoodsListVo> goodsList = new ArrayList<>();


        LambdaQueryWrapper<AgentStore> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(AgentStore::getStoreId)
                .eq(AgentStore::getAgentUserId, userId);
        List<AgentStore> agentStores = agentStoreMapper.selectList(wrapper);

        if (!agentStores.isEmpty()) {
            //查询商品信息
            List<Integer> storeIds = agentStores.stream().map(AgentStore::getStoreId).toList();
            List<VerifyGoodsListVo> list = goodsMapper.verifyGoodsList(storeIds, EStatus.on.getValue());

            if (!list.isEmpty()) {

                List<Integer> goodsIds = list.stream().map(VerifyGoodsListVo::getId).toList();

                //查询商品审核状态信息
                List<AdminVerify> adminVerifies = baseMapper.getVerifyTypeAndStatus(page, goodsIds, EAdminVerifyType.goods.getValue());

                Map<Integer, VerifyGoodsListVo> verifyGoodsMap = list.stream().collect(Collectors.toMap(VerifyGoodsListVo::getId, verifyGoodsListVo -> verifyGoodsListVo));

                //插入店铺名字
                List<Store> storeList = storeMapper.getStoreNameList(storeIds);
                Map<Integer, String> storeNameMap = storeList.stream().collect(Collectors.toMap(Store::getId, Store::getName));

                adminVerifies.forEach(adminVerify -> {

                    if (verifyGoodsMap.containsKey(adminVerify.getCommonId())) {
                        VerifyGoodsListVo verifyGoodsListVo = verifyGoodsMap.get(adminVerify.getCommonId());
                        //避免同一个商品不显示
                        VerifyGoodsListVo vo = BeanUtil.copyProperties(verifyGoodsListVo, VerifyGoodsListVo.class);

                        vo.setVerifyId(adminVerify.getId());
                        vo.setType(adminVerify.getType());
                        vo.setStatus(adminVerify.getStatus());
                        vo.setCreateTime(adminVerify.getCreateTime());
                        vo.setUpdateTime(adminVerify.getUpdateTime());
                        vo.setCover(AppConfigUtil.getUrlPrefix(vo.getCover()));
                        if (storeNameMap.containsKey(vo.getStoreId())) {
                            vo.setStoreName(storeNameMap.get(vo.getStoreId()));
                        }
                        goodsList.add(vo);
                    }
                });
            }
        }
        return goodsList;
    }


    @Override
    public List<VerifyActivityListVo> verifyActivityList(Long userId, PageDto dto) {
        Page page = new Page<>(dto.getPage(), dto.getSize());
        page.setSearchCount(false);

        List<VerifyActivityListVo> activityList = new ArrayList<>();

        LambdaQueryWrapper<AgentStore> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(AgentStore::getStoreId)
                .eq(AgentStore::getAgentUserId, userId);
        List<AgentStore> agentStores = agentStoreMapper.selectList(wrapper);

        if (!agentStores.isEmpty()) {
            //查询活动信息
            List<Integer> storeIds = agentStores.stream().map(AgentStore::getStoreId).toList();

            List<VerifyActivityListVo> list = storeActivityMapper.verifyActivityList(storeIds, EStatus.on.getValue());

            if (!list.isEmpty()) {
                List<Integer> activityIds = list.stream().map(VerifyActivityListVo::getId).toList();
                //查询活动审核状态信息 排好序
                List<AdminVerify> adminVerifies = baseMapper.getVerifyTypeAndStatus(page, activityIds, EAdminVerifyType.activity.getValue());

                //取除活动信息
                Map<Integer, VerifyActivityListVo> verifyActivityMap = list.stream().collect(Collectors.toMap(VerifyActivityListVo::getId, verifyActivityListVo -> verifyActivityListVo));

                //插入店铺名字
                List<Store> storeList = storeMapper.getStoreNameList(storeIds);
                Map<Integer, String> storeNameMap = storeList.stream().collect(Collectors.toMap(Store::getId, Store::getName));

                adminVerifies.forEach(adminVerify -> {

                    if (verifyActivityMap.containsKey(adminVerify.getCommonId())) {
                        VerifyActivityListVo verifyActivityListVo = verifyActivityMap.get(adminVerify.getCommonId());
                        //避免同一个活动不显示
                        VerifyActivityListVo vo = BeanUtil.copyProperties(verifyActivityListVo, VerifyActivityListVo.class);

                        vo.setVerifyId(adminVerify.getId());
                        vo.setType(adminVerify.getType());
                        vo.setStatus(adminVerify.getStatus());
                        vo.setCreateTime(adminVerify.getCreateTime());
                        vo.setUpdateTime(adminVerify.getUpdateTime());
                        if (storeNameMap.containsKey(vo.getStoreId())) {
                            vo.setStoreName(storeNameMap.get(vo.getStoreId()));
                        }
                        activityList.add(vo);
                    }
                });
            }
        }
        return activityList;
    }


    @Override
    public Integer updateVerifyStatus(Integer commonId, Integer type, Integer status) {
        LambdaUpdateWrapper<AdminVerify> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(AdminVerify::getCommonId, commonId)
                .eq(AdminVerify::getType, type)
                .set(AdminVerify::getStatus, status);

        return baseMapper.update(wrapper);
    }



    @Override
    public List<VerifyListVo> verifyList(Long userId, PageDto dto) {

        List<VerifyListVo> list = new ArrayList<>();
        User user = userService.getInfo(userId);

        if (ObjectUtil.isEmpty(user)){
            return list;
        }

        if (!CommonUtil.bitExistOffset(user.getRole(), EUserRole.admin.getValue())){
            return list;
        }

        String route = "/admin/adminVerify/activity/list";
        if (!authRuleService.authCheck(userId,route)){
            return list;
        }

        Page page = new Page<>(dto.getPage(), dto.getSize());
        page.setSearchCount(false);

        //查询审核信息列表
        LambdaQueryWrapper<AdminVerify> wrapper = new LambdaQueryWrapper<>();
        wrapper.last("ORDER BY FIELD(status, " + EAdminVerifyStatus.agentPass.getValue()+ " )DESC,FIELD(status,  " + EAdminVerifyStatus.initial.getValue()+")DESC ,update_time desc");
        List<AdminVerify> verifyList = baseMapper.selectList(page, wrapper);

        list = BeanUtil.copyToList(verifyList,VerifyListVo.class);
        
        if (!list.isEmpty()){
            //根据类型分组
            Map<Integer, List<VerifyListVo>> verifyTypeMap = list.stream().collect(Collectors.groupingBy(VerifyListVo::getType));

            //入驻审核map
            Map<Integer, AdminVerifyStoreEnterListVo> storeEnterMap = new HashMap<>();
            //店铺审核map
            Map<Integer, VerifyStoreListVo> storeMap = new HashMap<>();
            //商品审核map
            Map<Integer, VerifyGoodsListVo> goodsMap = new HashMap<>();
            //活动审核map
            Map<Integer, VerifyActivityListVo> activityMap = new HashMap<>();

            //查询驳回原因
            List<Integer> reasonIds = list.stream().map(VerifyListVo::getReasonId).distinct().filter(Objects::nonNull).toList();

            Map<Integer, String> reasonIdNameMap = new HashMap<>();
            if (!reasonIds.isEmpty()){
                reasonIdNameMap = reasonService.getIdNameMap(reasonIds);
            }

            //商家入驻审核列表
            if (verifyTypeMap.containsKey(EAdminVerifyType.storeEnter.getValue())){
                List<VerifyListVo> verifyListVo = verifyTypeMap.get(EAdminVerifyType.storeEnter.getValue());

                List<Integer> commonIds = verifyListVo.stream().map(VerifyListVo::getCommonId).distinct().toList();

                LambdaQueryWrapper<StoreEnter> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.in(StoreEnter::getId,commonIds);
                List<StoreEnter> storeEnters = storeEnterMapper.selectList(queryWrapper);

                if (!storeEnters.isEmpty()){
                    List<AdminVerifyStoreEnterListVo> storeEnterListVos = new ArrayList<>();

                    //申请人id
                    List<Long> userIds = storeEnters.stream().map(StoreEnter::getUserId).toList();

                    //代理人id
                    List<Long> agentUserId = storeEnters.stream().map(StoreEnter::getAgentUserId).filter(Objects::nonNull).toList();

                    //查询用户信息
                    List<Long> ids = Stream.concat(userIds.stream(), agentUserId.stream()).distinct().collect(Collectors.toList());
                    List<User> users = userMapper.getUserByIds(ids);
                    Map<Long, User> userMap = users.stream().collect(Collectors.toMap(User::getId, user1 -> user1));

                    for (StoreEnter storeEnter:storeEnters) {
                        AdminVerifyStoreEnterListVo vo = new  AdminVerifyStoreEnterListVo();

                        BeanUtil.copyProperties(storeEnter,vo);
                        vo.setIdCardImageUrl(AppConfigUtil.getUrlPrefix(storeEnter.getIdCardImage()));
                        vo.setBusinessLicenseUrl(AppConfigUtil.getUrlPrefix(storeEnter.getBusinessLicense()));
                        vo.setCommonId(storeEnter.getId());

                        if (userMap.containsKey(storeEnter.getUserId())){
                            vo.setNickname(userMap.get(storeEnter.getUserId()).getNickname());
                        }
                        if (userMap.containsKey(storeEnter.getAgentUserId())){
                            vo.setAgentUserNickName(userMap.get(storeEnter.getAgentUserId()).getNickname());
                        }
                        storeEnterListVos.add(vo);
                    }
                    storeEnterMap = storeEnterListVos.stream().collect(Collectors.toMap(AdminVerifyStoreEnterListVo::getCommonId, adminVerifyStoreEnterListVo -> adminVerifyStoreEnterListVo));
                }


            }

            //店铺审核列表
            if (verifyTypeMap.containsKey(EAdminVerifyType.store.getValue())){
                List<VerifyListVo> verifyListVo = verifyTypeMap.get(EAdminVerifyType.store.getValue());

                List<Integer> commonIds = verifyListVo.stream().map(VerifyListVo::getCommonId).distinct().toList();

                LambdaQueryWrapper<Store> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.in(Store::getId,commonIds);
                List<Store> storeList = storeMapper.selectList(queryWrapper);

                //地址map
                Map<String, String> areaMap = areaService.getNameMap();

                if (!storeList.isEmpty()){

                    List<VerifyStoreListVo> storeListVos = new ArrayList<>();

                    for (Store store:storeList) {
                        VerifyStoreListVo vo = BeanUtil.copyProperties(store, VerifyStoreListVo.class);
                        vo.setCityName(areaMap.get(store.getCity()));
                        vo.setProvinceName(areaMap.get(store.getProvince()));
                        vo.setDistrictName(areaMap.get(store.getDistrict()));
                        vo.setCover(AppConfigUtil.getUrlPrefix(store.getCover()));
                        vo.setCoverShow(AppConfigUtil.getUrlPrefix(store.getCoverShow()));
                        vo.setLogo(AppConfigUtil.getUrlPrefix(store.getLogo()));
                        vo.setStoreId(store.getId());
                        storeListVos.add(vo);
                    }
                    storeMap = storeListVos.stream().collect(Collectors.toMap(VerifyStoreListVo::getStoreId, verifyStoreListVo -> verifyStoreListVo));
                }


            }

            //商品审核列表
            if (verifyTypeMap.containsKey(EAdminVerifyType.goods.getValue())){

                List<VerifyListVo> verifyListVo = verifyTypeMap.get(EAdminVerifyType.goods.getValue());

                List<Integer> commonIds = verifyListVo.stream().map(VerifyListVo::getCommonId).distinct().toList();

                LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.in(Goods::getId,commonIds);
                List<Goods> goodsList = goodsMapper.selectList(queryWrapper);

                if (!goodsList.isEmpty()){

                    List<VerifyGoodsListVo> goodsListVos = new ArrayList<>();
                    List<Integer> storeIds = goodsList.stream().map(Goods::getStoreId).distinct().toList();
                    List<Store> stores = storeMapper.getStoreNameList(storeIds);
                    Map<Integer, Store> sMap= stores.stream().collect(Collectors.toMap(Store::getId, store -> store));

                    for (Goods goods:goodsList) {
                        VerifyGoodsListVo vo = BeanUtil.copyProperties(goods, VerifyGoodsListVo.class);
                        vo.setCover(AppConfigUtil.getUrlPrefix(goods.getCover()));
                        if (sMap.containsKey(goods.getStoreId())){
                            vo.setStoreName(sMap.get(goods.getStoreId()).getName());
                        }

                        goodsListVos.add(vo);
                    }
                    goodsMap = goodsListVos.stream().collect(Collectors.toMap(VerifyGoodsListVo::getId, verifyGoodsListVo -> verifyGoodsListVo));
                }


            }

            //活动审核列表
            if (verifyTypeMap.containsKey(EAdminVerifyType.activity.getValue())){

                List<VerifyListVo> verifyListVo = verifyTypeMap.get(EAdminVerifyType.activity.getValue());

                List<Integer> commonIds = verifyListVo.stream().map(VerifyListVo::getCommonId).distinct().toList();

                LambdaQueryWrapper<StoreActivity> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.in(StoreActivity::getId,commonIds);
                List<StoreActivity> storeActivityList = storeActivityMapper.selectList(queryWrapper);

                if (!storeActivityList.isEmpty()){

                    //查询店铺名字
                    List<Integer> storeIds = storeActivityList.stream().map(StoreActivity::getStoreId).toList();
                    List<Store> stores = storeMapper.getStoreNameList(storeIds);
                    Map<Integer, String> storeNameMap = stores.stream().collect(Collectors.toMap(Store::getId, Store::getName));

                    List<VerifyActivityListVo> activityListVos = new ArrayList<>();

                    for (StoreActivity storeActivity:storeActivityList) {
                        VerifyActivityListVo vo = BeanUtil.copyProperties(storeActivity, VerifyActivityListVo.class);
                        vo.setActivityType(storeActivity.getType());

                        if (storeNameMap.containsKey(storeActivity.getStoreId())){
                            vo.setStoreName(storeNameMap.get(storeActivity.getStoreId()));
                        }

                        activityListVos.add(vo);
                    }
                    activityMap = activityListVos.stream().collect(Collectors.toMap(VerifyActivityListVo::getId, verifyActivityListVo -> verifyActivityListVo));
                }
            }

            //插入入驻、店铺、商品、活动审核信息
            for (VerifyListVo listVo:list) {

                //插入驳回原因
                if (reasonIdNameMap.containsKey(listVo.getReasonId())){
                    listVo.setReason(reasonIdNameMap.get(listVo.getReasonId()));
                }

                if (storeEnterMap.containsKey(listVo.getCommonId()) && listVo.getType() == EAdminVerifyType.storeEnter.getValue()){
                    AdminVerifyStoreEnterListVo vo = storeEnterMap.get(listVo.getCommonId());
                    BeanUtil.copyProperties(vo,listVo,"id","status","type","remark","reasonId","reason","createTime","updateTime");
                    listVo.setStoreEnterName(vo.getName());
                    listVo.setStoreEnterTel(vo.getTel());
                }else if (storeMap.containsKey(listVo.getCommonId()) && listVo.getType() == EAdminVerifyType.store.getValue()){
                    VerifyStoreListVo vo = storeMap.get(listVo.getCommonId());
                    BeanUtil.copyProperties(vo,listVo,"id","status","type","remark","reasonId","reason","createTime","updateTime");
                    listVo.setStoreName(vo.getName());
                    listVo.setStoreCoverUrl(vo.getCover());
                    listVo.setCoverShowUrl(vo.getCoverShow());
                    listVo.setStoreStartTime(vo.getStartTime());
                    listVo.setStoreEndTime(vo.getEndTime());
                    listVo.setStoreTel(vo.getTel());
                }else  if (goodsMap.containsKey(listVo.getCommonId()) && listVo.getType() == EAdminVerifyType.goods.getValue()){
                    VerifyGoodsListVo vo = goodsMap.get(listVo.getCommonId());
                    BeanUtil.copyProperties(vo,listVo,"id","status","type","remark","reasonId","reason","createTime","updateTime");
                    listVo.setGoodsName(vo.getName());
                    listVo.setCoverUrl(vo.getCover());
                }else if (activityMap.containsKey(listVo.getCommonId()) && listVo.getType() == EAdminVerifyType.activity.getValue()){
                    VerifyActivityListVo vo = activityMap.get(listVo.getCommonId());
                    BeanUtil.copyProperties(vo,listVo,"id","status","type","remark","reasonId","reason","createTime","updateTime");
                    listVo.setActivityStartTime(vo.getStartTime());
                    listVo.setActivityEndTime(vo.getEndTime());
                }
            }
        }
        return list;
    }


    @Override
    public List<AdminVerifyListVo> listInfo(AdminVerifyListDto dto, Long userId) {

        List<AdminVerifyListVo> adminVerifyListVos = new ArrayList<>();

        Page<AdminVerify> page = new Page<>(dto.getPage(), dto.getSize());
        page.setSearchCount(false);
        LambdaQueryWrapper<AdminVerify> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(dto.getType() != null, AdminVerify::getType, dto.getType());
        userLambdaQueryWrapper.orderByDesc(AdminVerify::getCreateTime);
//        User user = userMapper.selectById(userId);
//        if (CommonUtil.bitExistOffset(user.getRole(), EUserRole.agent.getValue())) {
//            userLambdaQueryWrapper.ge(AdminVerify::getStatus,EVerifyStatus.pending);
//        }else {
//            userLambdaQueryWrapper.ge(AdminVerify::getStatus,EVerifyStatus.agentPass);
//        }
        List<AdminVerify> verifyList = baseMapper.selectPage(page, userLambdaQueryWrapper).getRecords();
        if (verifyList.isEmpty()) {
            return adminVerifyListVos;
        }

        adminVerifyListVos = BeanUtil.copyToList(verifyList, AdminVerifyListVo.class);
        Map<Integer, List<AdminVerifyListVo>> typeListMap = adminVerifyListVos.stream().collect(Collectors.groupingBy(AdminVerifyListVo::getType));

        // 分别设置店铺,商品,活动名称
        if (typeListMap.containsKey(EAdminVerifyType.store.getValue())) {
            List<AdminVerifyListVo> adminVerifies = typeListMap.get(EAdminVerifyType.store.getValue());
            List<Integer> sotreIdList = adminVerifies.stream().map(AdminVerifyListVo::getCommonId).toList();
            LambdaQueryWrapper<Store> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.select(Store::getId, Store::getName);
            lambdaQueryWrapper.in(Store::getId, sotreIdList);
            List<Store> stores = storeMapper.selectList(lambdaQueryWrapper);
            Map<Integer, String> storeIdNameMap = stores.stream().collect(Collectors.toMap(Store::getId, Store::getName));
            for (AdminVerifyListVo adminVerify : adminVerifies) {
                adminVerify.setName(storeIdNameMap.get(adminVerify.getCommonId()));
            }
        }
        if (typeListMap.containsKey(EAdminVerifyType.goods.getValue())) {
            List<AdminVerifyListVo> adminVerifies = typeListMap.get(EAdminVerifyType.goods.getValue());
            List<Integer> goodsIdList = adminVerifies.stream().map(AdminVerifyListVo::getCommonId).toList();
            LambdaQueryWrapper<Goods> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.select(Goods::getId, Goods::getName);
            lambdaQueryWrapper.in(Goods::getId, goodsIdList);
            List<Goods> goods = goodsMapper.selectList(lambdaQueryWrapper);
            Map<Integer, String> goodsIdNameMap = goods.stream().collect(Collectors.toMap(Goods::getId, Goods::getName));
            for (AdminVerifyListVo adminVerify : adminVerifies) {
                adminVerify.setName(goodsIdNameMap.get(adminVerify.getCommonId()));
            }
        }
        if (typeListMap.containsKey(EAdminVerifyType.activity.getValue())) {
            List<AdminVerifyListVo> adminVerifies = typeListMap.get(EAdminVerifyType.activity.getValue());
            List<Integer> activityIdList = adminVerifies.stream().map(AdminVerifyListVo::getCommonId).toList();

            LambdaQueryWrapper<StoreActivity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.select(StoreActivity::getId, StoreActivity::getStoreId, StoreActivity::getType);
            lambdaQueryWrapper.in(StoreActivity::getId, activityIdList);
            List<StoreActivity> activities = storeActivityMapper.selectList(lambdaQueryWrapper);

            Map<Integer, Integer> storeActivityTypeMap = activities.stream().collect(Collectors.toMap(StoreActivity::getId, StoreActivity::getType));
            List<Integer> storeIdList = activities.stream().map(StoreActivity::getStoreId).toList();
            Map<Integer, String> storeIdNameMap = storeService.getIdNameMap(storeIdList);

            Map<Integer, Integer> activityStoreIdMap = activities.stream().collect(Collectors.toMap(StoreActivity::getId, StoreActivity::getStoreId));

            // 活动类型
            Map<Integer, String> activityMap = EStoreActivityType.getMap();

            // 查询店铺名称
            for (AdminVerifyListVo adminVerify : adminVerifies) {

                Integer saType = storeActivityTypeMap.get(adminVerify.getCommonId());

                Integer storeTmpId = activityStoreIdMap.get(adminVerify.getCommonId());
                adminVerify.setName(storeTmpId == null ? null : storeIdNameMap.get(storeTmpId) + "-" + saType != null ? activityMap.get(saType) : "");

            }

        }
        // 存在入驻申请, 查询商家名称及提交的代理人id  (管理员审核入驻申请时,若不存在代理人id,审核时需指定一个代理人)
        if (typeListMap.containsKey(EAdminVerifyType.storeEnter.getValue())) {
            List<AdminVerifyListVo> adminVerifies = typeListMap.get(EAdminVerifyType.storeEnter.getValue());
            // 入驻申请表id
            List<Integer> storeEnterId = adminVerifies.stream().map(AdminVerifyListVo::getCommonId).toList();

            // 获取入驻申请的id及该申请提交的代理人Id
            LambdaQueryWrapper<StoreEnter> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(StoreEnter::getId, StoreEnter::getAgentUserId);
            queryWrapper.in(StoreEnter::getId, storeEnterId);
            List<StoreEnter> storeEnters = storeEnterMapper.selectList(queryWrapper);
            Map<Integer, Long> idAgentUserIdMap = storeEnters.stream().collect(Collectors.toMap(StoreEnter::getId, StoreEnter::getAgentUserId));
            for (AdminVerifyListVo adminVerifyListVo : adminVerifies) {
                adminVerifyListVo.setAgentUserId(idAgentUserIdMap.get(adminVerifyListVo.getId()));
            }
        }

        return adminVerifyListVos;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean adminVerify(AdminVerifyDto dto) {
        // 审核结果
        boolean pass = EVerifyResultType.pass.getValue().equals(dto.getResult());

        AdminVerify adminVerify = getById(dto.getId());
        // 管理员审核时,先判断代理人是否已经审核过
//        if (adminVerify.getStatus().equals(EVerifyStatus.pending.getValue())) {
//            throw new GeneralException(HttpStatus.agentPendingError);
//        }
//        if (!adminVerify.getStatus().equals(EVerifyStatus.agentPass.getValue())) {
//            throw new GeneralException(HttpStatus.invalidVerifyError);
//        }
        // 修改审核状态
        if (pass) {
            adminVerify.setStatus(EVerifyStatus.adminPass.getValue());
            adminVerify.setUpdateTime(TimeUtil.unixTime());
        } else {
            adminVerify.setReasonId(dto.getReasonId());
            adminVerify.setRemark(dto.getRemark());
            adminVerify.setStatus(EVerifyStatus.reject.getValue());
            adminVerify.setUpdateTime(TimeUtil.unixTime());
        }
        updateById(adminVerify);

        // 修改店铺,商品,活动的上架状态, 通过时上架商品,
        int shelves = pass ? EShelves.onSale.getValue() : EShelves.offShelf.getValue();
        if (adminVerify.getType().equals(EAdminVerifyType.store.getValue())) {

            if (shelves == EShelves.onSale.getValue()){
                //校验店铺是否有上架的商品和活动
                storeService.verifyStoreGoodsAndActivity(adminVerify.getCommonId());
            }

            //修改店铺上架状态
            LambdaUpdateWrapper<Store> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(Store::getShelves, shelves);
            updateWrapper.eq(Store::getId, adminVerify.getCommonId());
            storeMapper.update(updateWrapper);

            //修改商品店铺上架状态
            LambdaUpdateWrapper<Goods> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(Goods::getStoreShelves,shelves)
                    .eq(Goods::getStoreId,adminVerify.getCommonId());
            goodsMapper.update(wrapper);
        } else if (adminVerify.getType().equals(EAdminVerifyType.goods.getValue())) {
            LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(Goods::getShelves, shelves);
            updateWrapper.eq(Goods::getId, adminVerify.getCommonId());
            goodsMapper.update(updateWrapper);
        } else if (adminVerify.getType().equals(EAdminVerifyType.activity.getValue())) {
            LambdaUpdateWrapper<StoreActivity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(StoreActivity::getShelves, shelves);
            updateWrapper.eq(StoreActivity::getId, adminVerify.getCommonId());
            storeActivityMapper.update(updateWrapper);
        } else if (adminVerify.getType().equals(EAdminVerifyType.storeEnter.getValue())) {
            // 商家入驻申请,获取用户id,为用户添加商家角色
            Integer storeEnterId = adminVerify.getCommonId();
            LambdaQueryWrapper<StoreEnter> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(StoreEnter::getId, StoreEnter::getUserId, StoreEnter::getAgentUserId);
            queryWrapper.eq(StoreEnter::getId, storeEnterId);
            StoreEnter storeEnter = storeEnterMapper.selectOne(queryWrapper, false);
            if (storeEnter == null) {
                throw new GeneralException(HttpStatus.invalidVerifyError);
            }
            if(storeEnter.getAgentUserId() == null && dto.getResult() == 1 && dto.getAgentUserId() == null){
                throw new GeneralException(HttpStatus.agentNotNullError);
            }
            if (storeEnter.getAgentUserId() == null && dto.getAgentUserId() != null) {
                storeEnterMapper.update(Wrappers.<StoreEnter>lambdaUpdate().set(StoreEnter::getAgentUserId, dto.getAgentUserId())
                        .eq(StoreEnter::getId, storeEnterId));
            }
            if (dto.getResult() == 1){
                LambdaQueryWrapper<User> userQw = new LambdaQueryWrapper<>();
                userQw.select(User::getId, User::getRole);
                userQw.eq(User::getId, storeEnter.getUserId());
                User user = userMapper.selectOne(userQw);
                Integer role = user.getRole();
                role = CommonUtil.bitSetOffset(role, EUserRole.store.getValue());
                userService.upRole(user.getId(), role);

                // 清除用户缓存
                userService.clearUser(storeEnter.getUserId());

//                update(Wrappers.<AdminVerify>lambdaUpdate().set(AdminVerify::getReasonId,null).set(AdminVerify::getRemark,null)
//                        .eq(AdminVerify::getId, adminVerify.getId()));
            }

        }
        return true;
    }


    //代理人审核
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer agentUpdateStatus(StoreEnterUpdateStatusDto dto) {

        //审核未通过必须有驳回原因
        if (dto.getStatus() == EAdminVerifyStatus.notPass.getValue() && dto.getVerifyId() == null) {
            throw new GeneralException(HttpStatus.notCommonIdError);
        }

        AdminVerify adminVerify = new AdminVerify();

        LambdaUpdateWrapper<AdminVerify> wrapper = new LambdaUpdateWrapper<>();

        if (dto.getReasonId() != null){
            wrapper.set(AdminVerify::getReasonId, dto.getReasonId());
        }
        if (StrUtil.isNotEmpty(dto.getRemark())){
            wrapper.set(AdminVerify::getRemark, dto.getRemark());
        }
        wrapper.set(AdminVerify::getStatus, dto.getStatus());
        wrapper.set(AdminVerify::getUpdateTime,TimeUtil.unixTime());
        wrapper.eq(AdminVerify::getId, dto.getVerifyId())
                .eq(AdminVerify::getType, dto.getType());
        int i = baseMapper.update(wrapper);

        if (dto.getStatus() == EAdminVerifyStatus.notPass.getValue()) {
            LambdaQueryWrapper<AdminVerify> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.select(AdminVerify::getCommonId)
                    .eq(AdminVerify::getId, dto.getVerifyId());
            adminVerify = getOnly(queryWrapper);
        }

        //修改店铺上架状态
        if (dto.getType() == EAdminVerifyType.store.getValue() && dto.getStatus() == EAdminVerifyStatus.notPass.getValue()) {

            LambdaUpdateWrapper<Store> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Store::getId, adminVerify.getCommonId())
                    .set(Store::getShelves, EShelves.offShelf.getValue());
            storeMapper.update(updateWrapper);
        }

        //修改商品上架状态
        if (dto.getType() == EAdminVerifyType.goods.getValue() && dto.getStatus() == EAdminVerifyStatus.notPass.getValue()) {

            LambdaUpdateWrapper<Goods> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Goods::getId, adminVerify.getCommonId())
                    .set(Goods::getShelves, EShelves.offShelf.getValue());
            goodsMapper.update(updateWrapper);
        }

        //修改活动上架状态
        if (dto.getType() == EAdminVerifyType.activity.getValue() && dto.getStatus() == EAdminVerifyStatus.notPass.getValue()) {

            LambdaUpdateWrapper<StoreActivity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(StoreActivity::getId, adminVerify.getCommonId())
                    .set(StoreActivity::getShelves, EShelves.offShelf.getValue());
            storeActivityMapper.update(updateWrapper);
        }

        return i;
    }


    //查询申请人信息
    public Map<Integer,User> getUserMessage(List<Integer> storeIdList){
        Map<Integer,User> map = new HashMap<>();
        if (storeIdList.isEmpty()){
            return map;
        }
        //查询申请人信息
        LambdaQueryWrapper<StoreUser> storeUserWrapper = new LambdaQueryWrapper<>();
        storeUserWrapper.select(StoreUser::getUserId,StoreUser::getStoreId)
                .in(StoreUser::getStoreId,storeIdList)
                .eq(StoreUser::getRole,EStoreUserRole.possess.getValue());
        List<StoreUser> storeUsers = storeUserMapper.selectList(storeUserWrapper);
        Map<Integer,Long > ids = storeUsers.stream().collect(Collectors.toMap( StoreUser::getStoreId,StoreUser::getUserId));

        List<Long> userIds = storeUsers.stream().map(StoreUser::getUserId).toList();
        List<User> users = userMapper.getUserByIds(userIds);
        Map<Long, User> userMap = users.stream().collect(Collectors.toMap(User::getId, user -> user));

        ids.keySet().forEach(i -> {
            map.put(i,userMap.get(ids.get(i)));
        });
        return map;
    }
}
